import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    private String ip;
    private int port;
    private DatagramSocket socket = null;
    public UdpClient(String ip,int port) throws SocketException {
        this.ip = ip;
        this.port = port;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(this.ip),this.port);
            socket.send(requestPacket);

            DatagramPacket respondPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(respondPacket);
            String respond = new String(respondPacket.getData(),0,respondPacket.getLength());
            System.out.println(respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient client = new UdpClient("127.0.0.1",8888);
        client.start();
    }
}
